import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart' hide Response;
import 'package:ride_rex/net/common_global_url.dart';
import 'package:ride_rex/net/common_net_builder.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../constant.dart';
import '../net/common_net.dart';

class ApiConfig extends CommonApi {
  ApiConfig.config({required String ver}) : super(CommonGlobalUrl.getAppConfig, params: {'ver': ver});
  ApiConfig.strategy() : super(CommonGlobalUrl.getStrategy);
  ApiConfig.rongCloud() : super(CommonGlobalUrl.getRongCloudToken);
}

class CommonConfigService extends GetxService {
  static CommonConfigService get instance => Get.find();

  ///融云key
  String rongCloudKey = '';

  ///谷歌key
  String googleTranslationKey = '';

  Future init() async {
    String ver = CommonStorage().getString(StorageKey.spKeyVer, defaultValue: '0');
    dynamic json = await ApiConfig.config(ver: ver).get();
    if (json is Map && json['items'] is List) {
      json['items'].forEach((item) {
        if (item['name'] == 'rck') {
          rongCloudKey = item['data'] ?? '';
        }
        if (item['name'] == 'google_translation_key') {
          googleTranslationKey = item['data'] ?? '';
        }
      });
    }
  }

  ///谷歌翻译
  Future<String> translate({required String text}) async {
    if (text.empty) return '';

    ///取缓存
    String cache = CommonConfigService.instance.getTranslateResult(source: text);
    if (cache.isNotEmpty) return cache;

    ///调用翻译Api
    Response response = await Dio().post(CommonGlobalUrl.translate, queryParameters: {
      "key": googleTranslationKey,
      "target": DeviceInfoUtils().deviceLanguageCode, // 目标语言Code，从设备中获取当前语言。
      "q": text, // 被翻译的文案
      "format": 'text',
    });

    if (response.data is Map &&
        response.data['data'] is Map &&
        response.data['data']['translations'] is List &&
        (response.data['data']['translations'] as List).isNotEmpty) {
      String result = (response.data['data']['translations'] as List).first['translatedText'];

      ///保存缓存
      CommonConfigService.instance.saveTranslateResult(source: text, target: result);
      return result;
    }
    return '';
  }

  ///保存翻译结果
  Future<bool> saveTranslateResult({required String source, required String target}) async {
    return await CommonStorage().setString(_getKey(source), target);
  }

  ///获取翻译结果
  String getTranslateResult({required String source}) {
    if (source.empty) return '';
    return CommonStorage().getString(_getKey(source));
  }

  String _getKey(String source) {
    var bytes = utf8.encode(source); // data being hashed
    var digest = md5.convert(bytes);
    return digest.toString();
  }
}
